package com.jxb.netty.network.netty.http.client;

import com.jxb.netty.network.netty.http.server.HttpServer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;

public class HttpClient {
    public static final String HOST  = "127.0.0.1";
    private static final boolean SSL = false;

    public static void main(String[] args) throws InterruptedException {
        HttpClient httpClient = new HttpClient();
        httpClient.connect("127.0.0.1", HttpServer.port);
    }

    private void connect(String s, int port) throws InterruptedException {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new HttpClientCodec());
                            channel.pipeline().addLast("aggregator",new HttpObjectAggregator(10*1024*1024));
                            channel.pipeline().addLast(new HttpClientInboundHandler());
                        }
                    });
            ChannelFuture f = b.connect(s, port).sync();
            f.channel().closeFuture().sync();
        }finally {
            workGroup.shutdownGracefully();
        }
    }
}
